package com.pac.user.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.common.tools.MD5Tools;
import com.common.tools.StringTools;
import com.common.tools.TimeTools;
import com.common.util.ErrorNumber;
import com.common.util.LogicException;
import com.common.util.PropertyUtils;
import com.pac.doctor.DoctorKeyContent;
import com.pac.user.UserKeyContent;
import com.pac.user.bean.UserBean;
import com.pac.user.bean.UserDetailBean;
import com.pac.user.bean.UserHisBean;
import com.pac.user.dao.UserDetailDao;
import com.pac.user.service.UserDetailService;
import com.pac.user.service.UserHisService;
import com.pac.user.service.UserService;
import com.pac.weixin.bean.WxChatBean;
import com.pac.weixin.bean.WxDoctorSelBean;
import com.pac.weixin.service.WxChatService;
import com.pac.weixin.service.WxDoctorSelService;

/**
 * 用户明细信息service实现
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月16日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service(value = "userDetailService")
public class UserDetailServiceImpl implements UserDetailService {

	private static Logger logger = Logger
			.getLogger(UserDetailServiceImpl.class);

	@Autowired
	private UserDetailDao userDetailDao;

	@Autowired
	private UserService userService;

	@Autowired
	private UserHisService userHisService;

	@Autowired
	private WxChatService wxChatService;

	@Autowired
	private WxDoctorSelService wxDoctorSelService;

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public String addUserDetail(UserDetailBean userDetailBean) {
		if (null == userDetailBean) {
			logger.error("添加用户详细信息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userDetailBean.getName())) {
			logger.error("添加用户详细信息出错，姓名为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "姓名为空");
		}

		userDetailBean.setCreateDate(TimeTools.now());
		userDetailBean
				.setStage(UserKeyContent.USER_WX_STAGE_NO_MEDICAL_HISTORY);
		userDetailBean.setStageDate(TimeTools.now());
		userDetailBean.setObserve(UserKeyContent.USER_WX_OBSERVE_NO);
		String userDetailId = userDetailDao.addUserDetail(userDetailBean);

		// 更新用户明细ID到用户表
		if (!StringTools.isNull(userDetailBean.getUserId())) {
			UserBean userBean = new UserBean();
			userBean.setUserDetailId(userDetailId);
			userBean.setId(userDetailBean.getUserId());
			userBean.setNickname(userDetailBean.getName());
			userService.editUserBase(userBean);
		} else {
			UserBean userBean = new UserBean();
			userBean.setUserDetailId(userDetailId);
			userBean.setNickname(userDetailBean.getName());
			userBean.setCreateDate(TimeTools.now());
			userBean.setUserName(userDetailBean.getOpenId());
			userBean.setPassword(MD5Tools.MD5(userDetailBean.getOpenId()));
			userBean.setState(UserKeyContent.USER_STATUS_ACTIVE);
			userService.addUser(userBean);

		}

		// 是否是历史用户，历史用户直接推送问卷M6
		UserHisBean userHisBean = new UserHisBean();
		userHisBean.setMobilePhone(userDetailBean.getMobilePhone());
		UserHisBean userHisR = userHisService.findUserHis(userHisBean);
		if (null != userHisR) {
			// 推送六个月问卷
			String domain = PropertyUtils.getValue("system.domain.url");
			StringBuffer sixMonthSb = new StringBuffer();
			String url6 = domain
					+ "/weixin/qusetionnaire/gotoPage?pageName=questionnaire53&openId="
					+ userDetailBean.getOpenId();
			sixMonthSb.append("据您小产已经六个月了，康复情况如何？请完成如下随访表：");
			sixMonthSb.append("<a href='");
			sixMonthSb.append(url6);
			sixMonthSb.append("'>服务对象流产后6个月随访表</a>");

			WxChatBean chatToWxUser = new WxChatBean();
			chatToWxUser.setContent(sixMonthSb.toString());
			chatToWxUser.setOpenId(userDetailBean.getOpenId());
			chatToWxUser.setUserId("2");
			wxChatService.addChatFromPac(chatToWxUser);

			// 默认选择重医附二院
			WxDoctorSelBean wxDoctorSelBean = new WxDoctorSelBean();
			wxDoctorSelBean.setOpenId(userDetailBean.getOpenId());
			wxDoctorSelBean.setUserId(DoctorKeyContent.DOCTOR_CHONGYI_USER_ID);
			wxDoctorSelService.addWxDoctorSel(wxDoctorSelBean);

			userDetailId = "userhis";
		}

		return userDetailId;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean updateUserDetail(UserDetailBean userDetailBean) {
		if (null == userDetailBean) {
			logger.error("修改用户详细信息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userDetailBean.getId())
				&& StringTools.isNull(userDetailBean.getOpenId())) {
			logger.error("修改用户详细信息出错，用户详细信息ID和OpenId都为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL,
					"用户详细信息ID和OpenId都为空");
		}

		return userDetailDao.updateUserDetail(userDetailBean);
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRED)
	public boolean delUserDetail(UserDetailBean userDetailBean) {
		if (null == userDetailBean) {
			logger.error("删除用户详细信息出错，参数为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "参数为空");
		}

		if (StringTools.isNull(userDetailBean.getId())) {
			logger.error("删除用户详细信息出错，ID为空");
			throw new LogicException(ErrorNumber.PARAM_IS_NULL, "ID为空");
		}
		return userDetailDao.delUserDetail(userDetailBean);
	}

	@Override
	public List<UserDetailBean> queryUserDetail(UserDetailBean userDetailBean) {

		// 待提交诊断，默认查当天的
		if (UserKeyContent.USER_WX_STAGE_NO_DIAGNOSE.equals(userDetailBean
				.getStage())
				&& StringUtils.isEmpty(userDetailBean.getStageDateEnd())
				&& StringUtils.isEmpty(userDetailBean.getStageDateStart())) {

			String today = TimeTools.now("yyyy-MM-dd");
			String stageDateStart = today + " 00:00:00";
			String stageDateEnd = today + " 23:59:59";
			userDetailBean.setStageDateEnd(stageDateEnd);
			userDetailBean.setStageDateStart(stageDateStart);
		}

		return userDetailDao.queryUserDetail(userDetailBean);

	}

	@Override
	public UserDetailBean findUserDetail(UserDetailBean userDetailBean) {

		List<UserDetailBean> userDetailList = userDetailDao
				.queryUserDetail(userDetailBean);
		if (null != userDetailList && userDetailList.size() > 0) {
			return userDetailList.get(0);
		}

		return null;
	}

	@Override
	public UserDetailBean findUserDetailByOpenId(String openId) {
		if (StringTools.isNull(openId)) {
			return null;
		}

		UserDetailBean userDetailBean = new UserDetailBean();
		userDetailBean.setOpenId(openId);

		return findUserDetail(userDetailBean);
	}

	@Override
	public int countUserDetail(UserDetailBean userDetailBean) {
		return userDetailDao.countUserDetail(userDetailBean);
	}

}
